package com.example.demo.Service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.Service.IUserService;
import com.example.demo.entity.LoginUser;
import com.example.demo.entity.MsUser;
import com.example.demo.entity.params.UserRegisterParam;
import com.example.demo.entity.vo.UserInfoVo;
import com.example.demo.mapper.UserMapper;
import com.example.demo.util.JWTUtil;
import com.example.demo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper,MsUser>implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PasswordEncoder password;


    @Override
    public String createToken(String username, String password) {


        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(username,password);
        //调用UserDetailServiceImpl中的loadUserByUsername方法
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(authenticate == null){
            throw new RuntimeException("认证失败");
        }

        //getPrincipal()返回登录对象
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        String token = JWTUtil.createToken(loginUser.getMsUser());

        //缓存用户信息
        redisUtil.setCacheObject("user:"+loginUser.getMsUser().getUserId(),loginUser);

        return token;
    }

    @Override
    public MsUser selectByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public int register(UserRegisterParam userRegisterParam) {

        String word =  password.encode(userRegisterParam.getPassword());

        userRegisterParam.setPassword(word);

        return userMapper.addUser(userRegisterParam);
    }

    @Override
    public UserInfoVo selectById(Long userId) {
        return userMapper.selectById(userId);
    }
}
